<?php
/**
 * Created by PhpStorm.
 * User: 游贤川
 * Date: 2021/5/25
 * Time: 8:15
 */
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\HelpList;
use App\Models\LeavingMessage;
use App\Models\Prize;
use App\Models\PrizeUser;
use App\Models\RcUser;
use App\Models\RedBoxError;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Mockery\Exception;

class RcUserController extends Controller
{

    /**
     * 注册
     */
    /**
     *新增用户,邀请人加抽奖次数
     */
    public function AddUser(Request $request)
    {
        //验证
        $verify = [
            'open_id'=>'required',
            'head_img'=>'required',
            'name'=>'required',
        ];
        $regulation = [
            'open_id.required' => 'open_id必填',
            'head_img.required' => 'head_img必填',
            'name.required' => 'name必填',
        ];
        $validator = Validator::make($request->all(),$verify ,$regulation );
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $data = $request->input();
        $open_id = $data['open_id'];
        try{
            //判断用户是否存在,如果不存在创建用户
            $user = RcUser::query()->where(['open_id'=>$open_id])->select(['name','head_img','open_id','insert_time','luck_sum'])->first();
            if (!$user){
                //判断用户是否为新用户
                $new_user = $this->AppUser($open_id);
                if ($new_user->code != 200){
                    return $this->error($new_user->msg);
                }
                $user_data = [
                    'name'=>$data['name'],
                    'head_img'=>$data['head_img'],
                    'open_id'=>$data['open_id'],
                    'insert_time'=>$new_user->data?1:0,
                    'luck_sum'=>$new_user->data?1:0
                ];
                $user = RcUser::query()->create($user_data);
            }
            return $this->success($user,'用户创建成功');
        }catch (Exception $exception){
            Log::error('添加用户报错',[$exception->getMessage()]);
            return $this->error($exception->getMessage());
        }

    }

    /**
     * 抽奖接口
     */
    public function LuckDraw(Request $request)
    {
//        return $this->error('红包发放已达上线');
        //验证
        $verify = [
            'open_id'=>'required',
            'time'=>'required',
            'sign'=>'required',
        ];
        $regulation = [
            'open_id.required'=>'open_id必填',
            'time.required'=>'time必填',
            'sign.required'=>'sign必填',
        ];
        $validator = Validator::make($request->all(),$verify ,$regulation );
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        $start = 1;
        $data = $request->input();
        $open_id = $data['open_id'];
        $uuid = '6688a6a0-4790-bf70-9a08-d7679054f4bf';
        $u_sign = md5($data['open_id'].$uuid.$data['time']);
        if ($u_sign != $data['sign']) return  $this->error('非法操作');
        $time = Carbon::now()->toDateTimeString();
        $prize_user = PrizeUser::query()->where('created_at',$time)->exists();
        if ($prize_user){
            return $this->error('太快啦，请稍后重试');

        }
        //开启事务
        try {
            DB::beginTransaction();
            $user = RcUser::query()->where(['open_id' => $open_id])->select(['name','luck_sum'])->lockForUpdate()->first();
            if (!$user){
                return $this->error('用户不存在');
            }
            if ($user->luck_sum < 1){
                return $this->error('抽奖次数不足');
            }
            //扣除抽奖次数
            //得到所有奖品数量不为0的奖品
            $drawList = Prize::query()->whereRaw('sum > winners_num')->sharedLock()->get();
            //判断还有没有奖品
            $drawList_count = $drawList->count();
            if ($drawList_count == 0) {
                return $this->error('今日奖品已领完，请明日再来！');
            }
            RcUser::query()->where(['open_id'=>$open_id])->decrement('luck_sum',1);
            //得到所有概率之和
            $drawRate = $drawList->sum('probability');
            //随机抽取奖品
            $luck = rand($start, $drawRate);
            //查看是抽中的几号商品
            foreach ($drawList as $draw) {
                if (!empty($draw['probability'])) {
                    if ($luck >= $start && $luck <= $start + $draw['probability'] - 1) {
                        $draw_id = $draw['id'];
                        $draw_type = $draw['type'];
                        $money = $draw['money'];
                        break;
                    }
                    $start += $draw['probability'];
                }
            }
            //奖品中奖数量+1
            Prize::query()->where(['id' => $draw_id])->increment('winners_num');
            //添加中奖数据
            $data = [
                'user_openid'=>$open_id,
                'prize_id'=>$draw_id,
                'type'=>$draw_type,
                'status'=>0
            ];
            //添加中奖记录
            $model = PrizeUser::query()->create($data);
            $draw->prize_user_id = $model->id;
            DB::commit();
            return $this->success($draw,'成功');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('抽奖错误',[$e->getMessage()]);
            return $this->error('抽奖失败, ' . $e->getMessage());
        }
    }

    /**
     * 发放微信红包
     */
    public function SendRedBox(Request $request)
    {
//        return $this->error('红包发放已达上线');
        $verify = [
            'open_id'=>'required',
            'prize_user_id'=>'required',
        ];
        $regulation = [
            'open_id.required' => 'open_id必填',
            'prize_user_id.required' => '中奖记录id必填',
        ];
//        return $this->error('请稍后重试');
        $validator = Validator::make($request->all(),$verify ,$regulation );
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        $data = $request->input();
        try{
            DB::beginTransaction();
            $ip = $_SERVER["REMOTE_ADDR"];
            $prize_user = PrizeUser::query()->with('prize')->where(['type'=>2,'user_openid'=>$data['open_id'],'id'=>$data['prize_user_id']])->select(['status','prize_id'])->lockForUpdate()->first();
            if (!$prize_user){
                return $this->error('记录不存在');
            }
            if ($prize_user->status == 1){
                return $this->error('红包已发放');
            }
            $red_box = $this->RedBox($data['open_id'],$prize_user->prize->money);
            Log::info('红发发放记录',[$red_box,$data,$ip]);
            if ($red_box->code == 200){
                $str['status'] = 1;
                $str['payment_no'] = $red_box->data->paymentNo;
                $success_prize_user = PrizeUser::query()->where(['id'=>$data['prize_user_id']])->update($str);
                DB::commit();
                return $this->success('','成功');
            }else{
                if (isset($red_box) && !empty($red_box) && $red_box->code != 200){
                    $error = [
                        'prize_user_id'=>$prize_user->id,
                        'open_id'=>$data['open_id'],
                        'money'=>$prize_user->prize->money,
                        'error_msg'=>$red_box->msg
                    ];
                    DB::commit();
                    RedBoxError::query()->create($error);
                    return $this->error('红包发放失败，次日将进行补发');
                }
            }
        }catch (\Exception $e){
            DB::rollBack();
            Log::info('红包发放接口异常：',[$e->getMessage()]);
            return $this->error($e->getMessage());
        }

    }

    public function RedBox($open_id,$money)
    {
        $params = [
            'appId'=>'wxf2a6206f7e2fd712',
            'openId'=>$open_id,
            'amount'=>$money*100,
            'remark'=>'KCC选拔赛宝箱活动'
        ];
        $client = new Client(['base_uri' => 'http://miniapps.yili.com:8130' ,'timeout'  => 5.0,]);
        $response = $client->post('/api/currencyAward',['form_params' => $params]);
        $data = json_decode($response->getBody()->getContents());

        return $data;
    }


    /**
     * 用户信息接口
     */

    public function AppUser($open_id)
    {

        $time = '2021-7-5 00:00:00';
        $client = new Client(['base_uri' => 'https://amxshop.yili.com/api/user/isNewMember?openId='.$open_id.'&time='.$time.'' ,'timeout'  => 5.0,]);
        $response = $client->get('');
        $data = $response->getBody()->getContents();
        return json_decode($data);

    }

    /**
     * 中奖列表
     */

    public function PrizeUser(Request $request)
    {
        $open_id = $request->input('open_id');
        $models = PrizeUser::query()->with(['prize'])->where(['user_openid'=>$open_id])->get()->toArray();
        $list = [];
        foreach ($models as $k=>$v){
            $list[$k]['prize_user_id'] = $v['id'];
            $list[$k]['prize'] = $v['prize']['name'];
            $list[$k]['status'] = $v['status'];
            $list[$k]['time'] = date('m-d H:i',strtotime($v['created_at']));
            $list[$k]['type'] = $v['type'];
        }
        return $this->success($list,'中奖列表');
    }


     /**
      * 奖品配置
      */

     public function Prize()
     {
         $list = Prize::query()->get();
         return $this->success($list,'成功');
     }

     /**
      * 留资
      */

     public function LeavingMessage(Request $request)
     {
         $validator = Validator::make($request->all(), [
             'open_id' => 'required',
             'prize_user_id' => 'required'
         ], [
             'open_id.required'=>'用户open_id必填',
             'prize_user_id.required'=>'奖品id必填'
         ]);
         if ($validator->fails()) {
             return $this->error($validator->errors()->first());
         }
         $data = $request->input();
         $data['user_openid'] = $data['open_id'];
         $message = LeavingMessage::query()->where(['user_openid'=>$data['open_id'],'prize_user_id'=>$data['prize_user_id']])->exists();
         if ($message){
             return $this->error('已留资');
         }
         $leaving = LeavingMessage::query()->create($data);
         if ($leaving){
             PrizeUser::query()->where(['id'=>$data['prize_user_id'],'user_openid'=>$data['open_id']])->update(['status'=>1]);
         }
         return $this->success($leaving,'成功');
     }

    /**
     * 添加邀请记录
     */

    public function AddParent(Request $request)
    {

        //验证
        $verify = [
            'open_id'=>'required',
            'parent_openid'=>'required',
        ];
        $regulation = [
            'open_id.required' => 'open_id必填',
            'parent_openid.required' => 'parent_openid必填',
        ];
        $validator = Validator::make($request->all(),$verify ,$regulation );
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $data = $request->input();

        $user = RcUser::query()->where(['open_id'=>$data['open_id']])->select('open_id','insert_time')->first();
        if (!$user){
            return $this->error('用户不存在');
        }
        if ($data['open_id'] == $data['parent_openid']){
            return  $this->error('不能自己邀请自己哟~');
        }
        //判断邀请人是否存在
        $parent_user = RcUser::query()->where(['open_id'=>$data['parent_openid']])->first();
        if (!$parent_user){
            return $this->error('邀请人不存在');
        }
        if ($user->insert_time == 0){
            return $this->error('助力失败，只有新用户才有助力资格哟～');
        }
            $prize_user = PrizeUser::query()->where(['user_openid'=>$data['open_id']])->exists();
            if ($prize_user){
             $this->error('助力失败，只有新用户才有助力资格哟～');
            }
            //查找用户今日是否受邀请过
            $time = Carbon::now()->toDateString();
            $help = HelpList::query()->where(['user_openid'=>$data['open_id']])->exists();
            if($help){

               return  $this->error('助力失败，您已为好友助力过喽～');
            }
            $now_parent_user_count = HelpList::query()->where(['parent_openid'=>$data['parent_openid'],'time'=>$time])->count();
            if ( $now_parent_user_count<10){
                HelpList::query()->create([
                    'user_openid'=>$user->open_id,
                    'parent_openid'=>$data['parent_openid'],
                    'time'=>$time
                ])
                ;
                //邀请人抽奖次数加1
                $parent_user->increment('luck_sum',1);
            }else{
                return $this->error('助力失败，您的好友已超过今日可助力次数喽～');
            }

        return $this->success('','助力成功');
    }


    public function TestWx()
    {
        $template =  \App\Models\WxMessage::query()->first();
        $token = env('WX_TOKEN');
        $client = new Client(['','timeout'  => 5.0,]);
        //拿到微信access_token
        $response1 = $client->get('https://amxshop.yili.com/api/user/getAccessToken',['headers'=>['accessToken'=>$token]]);
        $data = json_decode($response1->getBody()->getContents());
        $wx_token = $data->data;
        $wx_url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$wx_token;
        $data_str = explode('|',$template->data);
        $data = [];
        $data['thing1']['value'] = $data_str[0];
        $data['thing2']['value'] = $data_str[1];
        $data['thing4']['value'] = $data_str[2];
        $params = [
            'touser'=>'osgSC4vsW_uZWHXsyeqmIoNL2E_k',
            'template_id'=>$template->template_id,
            'data'=>$data
        ];
        $client = new Client(['','timeout'  => 5.0,]);
        $response2 = $client->post($wx_url,['json'=>$params]);
//        $content = json_decode($response2->getBody()->getContents());
        dd(json_decode($response2->getBody()->getContents()));
    }


    }
